package com.vf.cloud.server.colony.server;

import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.jfinal.kit.StrKit;
import com.vf.cloud.common.pool.ProssPool;
import com.vf.cloud.server.adapter.AdapterServer;
import com.vf.cloud.server.colony.channel.NodeChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NServer implements Runnable {

	private EventLoopGroup group;
	private ExecutorService executor;
	private ChannelFuture future;
	

	/**
	 * 0-停止 1-正在启动 2-运行中 3-停止中
	 */
	private int status = 0;

	public void run() {
		executor = Executors.newFixedThreadPool(1);
		try {
			executor.submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					start();
					return "";
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void start() {
		try {

			status = 1;
			
			log.info(">>>正在启动NodeServer: 6666");
			
	        // 首先，netty通过ServerBootstrap启动服务端
	        Bootstrap client = new Bootstrap();
	        
	        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
	        group = new NioEventLoopGroup();
	        client.group(group );
	        
	        client.channel(NioSocketChannel.class);
	        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
	        client.handler(new NodeChannelInitializer());
	        future = client.connect("localhost", 8080).sync();
			log.info(">>>NodeServer启动成功：" + future.channel());
			status = 2;
			AdapterServer.getInstance().onChange();
		} catch (InterruptedException e) {
			e.printStackTrace();
			status = 3;
			log.error(">>>NodeServer启动异常：", e);
			stop();
		} finally {
		}
	}

	public void stop() {
		status = 3;
		if (future != null) {
			 try {
				future.channel().closeFuture().sync();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		group.shutdownGracefully();
		if (executor != null)
			executor.shutdownNow();
		checkStop();
	}

	public void restart() {
		run();
	}

	public int getStatus() {
		return status;
	}

	private ScheduledExecutorService scheduledExecutor;

	private void checkStop() {
		scheduledExecutor = new ScheduledThreadPoolExecutor(1);
		scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
			@Override
			public void run() {
				if (StrKit.isBlank(ProssPool.getPid("6666"))) {
					status = 0;
					scheduledExecutor.shutdown();
				}
			}
		}, 0, 1, TimeUnit.SECONDS);
	}
	
	public void send() {
		
	}

}
